import { AnimationClip, Sprite, animation } from "cc"

import { TILE_WITTH } from "../TS/Tile/TileManager"
import ResourceManager from "../Runtime/ResourceManager"

export const ANIMATION_SPEED = 1 / 8

export default class State {
  animationClip: AnimationClip
  constructor(
    private fsm,

    private path,
    private wrapmode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal
  ) {
    this.init()
  }

  async init() {
    this.initPlayer()
  }
  async initPlayer() {
    const promise = ResourceManager.loadRes(this.path)
    this.fsm.waitingList.push(promise)
    const imgs = await promise

    this.animationClip = new AnimationClip()
    this.animationClip.name = this.path
    this.animationClip.wrapMode = this.wrapmode
    this.animationClip.duration = imgs.length * ANIMATION_SPEED
    const track = new animation.ObjectTrack()
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty("spriteFrame")
    const frames = imgs.map((item, index) => {
      return [ANIMATION_SPEED * index, item]
    })
    track.channel.curve.assignSorted(frames)
    this.animationClip.addTrack(track)
  }

  run() {
    this.fsm.animationComp.defaultClip = this.animationClip
    this.fsm.animationComp.play()
  }
}
